package cn.thens.kdroid.core.app

import cn.thens.kdroid.core.log.Logdog
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.exceptions.OnErrorNotImplementedException
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers

object Rx {
    internal fun initialize() {
        RxJavaPlugins.setErrorHandler { e ->
            val throwable = if (e is OnErrorNotImplementedException) e.cause else e
            if (throwable != null) Logdog.error(throwable)
        }
    }

    inline fun <T> single(crossinline fn: () -> T): Single<T> {
        return Single.create<T> { it.onSuccess(fn()) }.subscribeOn(Schedulers.io())
    }

    @Deprecated("use single<Unit>", ReplaceWith("Rx.single<Unit>(fn)"))
    inline fun completable(crossinline fn: () -> Unit): Completable {
        return Completable.create {
            fn()
            it.onComplete()
        }.subscribeOn(Schedulers.io())
    }
}